﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp1.Utils
{
    public static class HexUtil
    {
        /// <summary>
        /// 将字符串转换为十六进制字符串（ASCII编码）
        /// </summary>
        public static string StringToHex(string input)
        {
            if (string.IsNullOrEmpty(input))
                return string.Empty;

            byte[] bytes = Encoding.ASCII.GetBytes(input);
            return string.Concat(bytes.Select(b => b.ToString("X2")));
        }

        /// <summary>
        /// 将十六进制字符串还原为普通字符串（ASCII编码）
        /// </summary>
        public static string HexToString(string hex)
        {
            if (string.IsNullOrEmpty(hex))
                return string.Empty;

            // 去掉可能存在的空格、破折号等分隔符
            hex = hex.Replace(" ", "").Replace("-", "");

            if (hex.Length % 2 != 0)
                throw new ArgumentException("无效的十六进制字符串长度。");

            byte[] bytes = Enumerable
                .Range(0, hex.Length / 2)
                .Select(i => Convert.ToByte(hex.Substring(i * 2, 2), 16))
                .ToArray();

            return Encoding.ASCII.GetString(bytes);
        }

        /// <summary>
        /// 将字节数组转换为十六进制字符串
        /// </summary>
        public static string BytesToHex(byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0)
                return string.Empty;

            return string.Concat(bytes.Select(b => b.ToString("X2")));
        }

        /// <summary>
        /// 将十六进制字符串转换为字节数组
        /// </summary>
        public static byte[] HexToBytes(string hex)
        {
            if (string.IsNullOrEmpty(hex))
                return Array.Empty<byte>();

            hex = hex.Replace(" ", "").Replace("-", "");

            if (hex.Length % 2 != 0)
                throw new ArgumentException("无效的十六进制字符串长度。");

            return Enumerable
                .Range(0, hex.Length / 2)
                .Select(i => Convert.ToByte(hex.Substring(i * 2, 2), 16))
                .ToArray();
        }
    }
}
